<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/2/16
 * Time: 10:24
 */
/*
 * 用户信息
 */
namespace Futures\Controller;
use Think\Controller;
use Common\Api\SendSMSApi;

class UserController extends BaseController
{
    public function register(){
        $this->display();
    }
    /*
     * 提交注册用户
     */
    public function user_register_add(){
        $user_auth= cookie('user_auth');
        $user_id= $user_auth['uid'];
        $phone=I('post.phone');
        $password=I('post.password');
        $repassword=I('post.repassword');
        if($password!=$repassword){
        	$arr['status']=false;
        	$arr['msg']="密码不相同";
        	$this->ajaxReturn($arr,'JSON');
        }
        $code=I('post.code');
        if(!$this->is_mobile($phone)){
        	$arr['status']=false;
        	$arr['msg']="手机号码不匹配";
           	$this->ajaxReturn($arr,'JSON');
        }
		if(!$this->exist_mobile($phone)){
        	$arr['status']=false;
        	$arr['msg']="手机号码已存在";
           	$this->ajaxReturn($arr,'JSON');
        }
        if(empty($password)){
        	$arr['status']=false;
        	$arr['msg']="密码不能为空";
           	$this->ajaxReturn($arr,'JSON');
        }
        if(empty($code)){
        	$arr['status']=false;
        	$arr['msg']="验证码不能为空";
           	$this->ajaxReturn($arr,'JSON');
       }//验证码不能为空
       $sendsms=new SendSMSApi();
        if(!$sendsms->checkCode($phone,$code)){
		//if(0){
       	    $arr['status']=false;
        	$arr['msg']="验证码不匹配";
          	$this->ajaxReturn($arr,'JSON');
       	}
        $futures_pwd=md5($password.$user_id);
        $where['id']=$user_id;
        $data['mobile']=$phone;
        $data['futures_pwd']=$futures_pwd;
        if(M('follow')->where($where)->save($data)===false){
            $arr['status']=false;
        	$arr['msg']="注册失败";
           	$this->ajaxReturn($arr,'JSON');
        }else{
			$this->register_card($user_id,1);
           	$arr['status']=true;
        	$arr['msg']="注册成功";
        	$this->ajaxReturn($arr,'JSON');
        }
    }
    /*
     * 个人信息
     */
    public function user_info(){
        $user_auth= cookie('user_auth');
        $user_id= $user_auth['uid'];
        $info=M('follow')->where(array('id'=>$user_id))->find();
        $this->assign('info',$info);
		
		$url=get_url();
		$pos = strpos($url,'?');
		if(false===$pos){
			$share_url = $url.'?s=/Index/index/shareuserid/'.base64_encode($user_id);
		}else{
			$p = strpos($url,'shareuserid');
			if(false===$p){
				$share_url = $url.'/shareuserid/'.base64_encode($user_id);
			}else{
				$share_url = mb_substr($url,0,$p).'shareuserid/'.base64_encode($user_id);;
			}
		}
		
		$this->assign('share_url',$share_url);
        $this->display();
    }
    /**
     * 修改交易密码
     */
    public function reset_password() {
        $user_auth= cookie('user_auth');
        $user_id= $user_auth['uid'];
        $password=I('post.password');
        if(empty($password)){ $this->ajaxReturn (9,'JSON');}
        $repassword=I('post.repassword');
        if(empty($repassword)){ $this->ajaxReturn (8,'JSON');}
        $repasswordtwo=I('post.repasswordtwo');
        if(empty($repasswordtwo)){ $this->ajaxReturn (7,'JSON');}
        $where['id']=array('eq',$user_id);
        $where['status']=array('eq',1);
        $futures_pwd=M('follow')->where($where)->getfield('futures_pwd');
        $passordold=md5($password.$user_id);
        if($futures_pwd!=$passordold){//原密码出错
            $this->ajaxReturn (1,'JSON');
        }
        if($repassword!=$repasswordtwo){//新密码不相同
            $this->ajaxReturn (2,'JSON');
        }
        $newpassword=md5($repassword.$user_id);
        $data['futures_pwd']=$newpassword;
        if(M('follow')->where($where)->save($data)===false){
            $this->ajaxReturn (4,'JSON');
        }else{
            $this->ajaxReturn (3,'JSON');
        }
    }
    /**
     * 发送短信验证码
     */
    public function send_verify(){
        $mobile=I('post.mobile');
        $sendsms=new SendSMSApi();
        $res = $sendsms->sendCode($mobile);
    }
    /*
	 *验证手机是否有用
	 */
    private function is_mobile($string){
        if (!empty($string)) {
			
            return preg_match('/^1[3|4|5|7|8][0-9]\d{8}$/', $string);
			
        }
        return FALSE;
    }
	/*
	*验证手机号码是否存在
	*/
	private function exist_mobile($string){
		if(!empty($string)){
			$where['mobile']=$string;
			if($one=M('follow')->where($where)->find()){
				return FALSE;
			}
			return TRUE;
		}
		return FALSE;
	}
    /*
     * 绑定银行卡
     */
    public function bank_binding(){
        $user_auth= cookie('user_auth');
        $user_id= $user_auth['uid'];
        $where['user_id']=$user_id;
        if(M('futures_user_bank')->where($where)->find()){//判断是否已绑定银行卡
            	redirect(U('User/bank_index'));
            	exit;
         };
        if($_POST) {
            $data = $_POST;
            if(empty($data['bank_name'])){
				$arr['status']=false;
        		$arr['msg']="银行名称不能为空";
           		$this->ajaxReturn($arr,'JSON');
			}
			if(empty($data['bank_realname'])){
				$arr['status']=false;
        		$arr['msg']="持卡人不能为空";
           		$this->ajaxReturn($arr,'JSON');
			}
			if(strlen($data['bank_card'])!=16 && strlen($data['bank_card'])!=18 && strlen($data['bank_card'])!=19){
				$arr['status']=false;
        		$arr['msg']="银行卡号是16、18或19位";
           		$this->ajaxReturn($arr,'JSON');
			}
			if(strlen($data['id_card'])!=15 && strlen($data['id_card'])!=18){
				$arr['status']=false;
        		$arr['msg']="身份证不符合要求";
           		$this->ajaxReturn($arr,'JSON');
			}
			if(empty($data['outlets_name'])){
				$arr['status']=false;
        		$arr['msg']="开户行地址不能为空";
           		$this->ajaxReturn($arr,'JSON');
			}
			if(empty($data['pro_name'])){
				$arr['status']=false;
        		$arr['msg']="开户省份不能为空";
           		$this->ajaxReturn($arr,'JSON');
			}
			if(empty($data['city_name'])){
				$arr['status']=false;
        		$arr['msg']="开户市不能为空";
           		$this->ajaxReturn($arr,'JSON');
			}
            $data['add_time'] = time();
            $data['user_id'] = $user_id;
            if(M('futures_user_bank')->add($data)){
               	$arr['status']=true;
        		$arr['msg']="添加银行卡成功";
           		$this->ajaxReturn($arr,'JSON');
            }else{
              	$arr['status']=false;
        		$arr['msg']="添加银行卡失败";
           		$this->ajaxReturn($arr,'JSON');
            }
        }
        $this->display();
    }
    //提现页面
    public function bank_index(){
    	$user_auth= cookie('user_auth');
        $user_id= $user_auth['uid'];
        $where['id']=$user_id;
     	$money=M('follow')->where($where)->getField('money');//余额
     	$futures_where['user_id']=$user_id;
     	$list=M('futures_user_bank')->where($futures_where)->find();//查询银行数据
     	if(!$list){//如果还未绑定银行卡，跳转绑定页面
     		$url=__CONTROLLER__.'/bank_binding';
			//header("Location:$url");
            redirect(U("User/bank_binding"));
			exit;
		}
     	$list['bank_card']=substr($list['bank_card'],0,4);
     	session('bank_id',$list['id']);
     	$this->assign('money',$money);
     	$this->assign('list',$list);
		$this->display();
	}
	public function verify(){
		$Verify =     new \Think\Verify();
		$Verify->fontSize = 40;
		$Verify->length   = 4;
		$Verify->useNoise = false;
		$Verify->entry();
	}
	//提现数据处理
	public function draw_money(){
		$user_auth= cookie('user_auth');
        $data['user_id']=$user_id= $user_auth['uid'];
        $where['id']=$user_id;
     	$follow=M('follow')->where($where)->find();//账户信息
		$data['bank_id']=$bank_id=I('post.bank_id');
		$balance_money=I('post.balance_money');//余额
		$cash_money=$drawing_money=I('post.drawing_money',0,'doubleval');//提款金额
		$password=I('post.password');
		// $code=I('post.code');
		// if(!$this->check_verify($code)){
		// 	$arr['status']=false;
  //       	$arr['msg']="验证码出错";
  //          	$this->ajaxReturn($arr,'JSON');
		// }
		if($bank_id!=session('bank_id')){
			$arr['status']=false;
        	$arr['msg']="绑定银行卡出错";
           	$this->ajaxReturn($arr,'JSON');
		}
		if($follow['futures_pwd']==''){
			$arr['status']=false;
        	$arr['msg']="提款密码未设置";
           	$this->ajaxReturn($arr,'JSON');
		}
		if($drawing_money>$follow['money']){
			$arr['status']=false;
        	$arr['msg']="提款金额大于余额";
           	$this->ajaxReturn($arr,'JSON');
		}
		if($drawing_money<100 || $drawing_money>5000){
			$arr['status']=false;
        	$arr['msg']="提款金额在100-5000元";
           	$this->ajaxReturn($arr,'JSON');
		}
		$drawpassword=md5($password.$user_id);
		if($follow['futures_pwd']!=$drawpassword){
			$arr['status']=false;
        	$arr['msg']="提款密码出错";
           	$this->ajaxReturn($arr,'JSON');
		}
		$data['is_pay']=0;
		$data['remark']='等待提现...';
		$data['add_time']=time();
		//计算手续费
		$handling_fee = $cash_money*0.01;
		if($handling_fee<2){
			$handling_fee = 2;
		}else{
			$handling_fee = $cash_money*0.01;
		}
		$data['handling_fee'] = $handling_fee;
		$data['money'] = $cash_money-$data['handling_fee'];
		if(M('futures_withdrawals')->add($data)){//生成提款订单
			$openid=$follow['openid'];
			$money=-$drawing_money;
			$type=2;
			$note='提现';
			$blocked_fund['blocked_fund'] = $follow['blocked_fund']-$money;
			M('follow')->where($where)->save($blocked_fund);		//将提现金额写入冻结资金
			modify_account($openid,-$data['money'],$type,$note);		//交易记录
            modify_account($openid,-$data['handling_fee'],9,'提现手续费');     //交易记录
			$arr['status']=true;
        	$arr['msg']="提交申请成功，24小时内到达你的账户";

            $sendsms=new SendSMSApi();
            $nickname = $user_auth['nickname'];
            $mobile='18980439909';
            $content = '客户'.$nickname.'在'.date('Y-m-d H:i:s').'提现'.$money.'元。';
            $res = $sendsms->sendqSMS($mobile,$content);

           	$this->ajaxReturn($arr,'JSON');
		}else{
			$arr['status']=false;
        	$arr['msg']="插入提现操作失败";
           	$this->ajaxReturn($arr,'JSON');
		}	
	}
	private function check_verify($code, $id = ''){    
		$verify = new \Think\Verify();    
		return $verify->check($code, $id);
	}
    public function pwd_login(){
        $user_auth= cookie('user_auth');
        $user_id = $user_auth['uid'];
        //获取密码
        $pwd = I('post.pwd');
        $repwd = md5($pwd.$user_id);
        //数据库密码
        $f_pwd = M('Follow')->where(array('id'=>$user_id))->getField('futures_pwd');
        if($repwd==$f_pwd){
            session($user_auth['uid'].'_futures_pwd',1);
            $re = array('status'=>true,'info'=>'');
        }else{
            $re = array('status'=>false,'info'=>'密码确认失败');
        }
        $this->ajaxReturn($re,'json');
    }
		/**
	* 
	* 找回密码
	* 
	* @return
	*/
	public function find_pwd(){
        $user_auth= cookie('user_auth');
        $user_id = $user_auth['uid'];
        
		if(IS_POST){
			 $phone=I('post.phone');
        	 $password=I('post.password');
        	 $repassword=I('post.repassword');
        	 if($password!=$repassword){
        		$arr['status']=false;
        	   	$arr['msg']="密码不相同";
        		$this->ajaxReturn($arr,'JSON');
        	}
        	$code=I('post.code');
        	if(!$this->is_mobile($phone)){
        		$arr['status']=false;
        		$arr['msg']="手机号码不匹配";
           		$this->ajaxReturn($arr,'JSON');
        	}
        	if(empty($password)){
        		$arr['status']=false;
        		$arr['msg']="密码不能为空";
           		$this->ajaxReturn($arr,'JSON');
        	}
        	if(empty($code)){
        		$arr['status']=false;
        		$arr['msg']="验证码不能为空";
           		$this->ajaxReturn($arr,'JSON');
       		}//验证码不能为空
       		$sendsms=new SendSMSApi();
       		if(!$sendsms->checkCode($phone,$code)){
       	    	$arr['status']=false;
        		$arr['msg']="验证码不匹配";
          		$this->ajaxReturn($arr,'JSON');
       		}
        	$futures_pwd=md5($password.$user_id);
        	$where['id']=$user_id;
        	$where['mobile']=$phone;
        	$data['futures_pwd']=$futures_pwd;
            $res = M('Follow')->where($where)->save($data);
        	if($res===false){
            	$arr['status']=false;
        		$arr['msg']="找回密码失败";
           		$this->ajaxReturn($arr,'JSON');
        	}else{
           		$arr['status']=true;
        		$arr['msg']="找回密码成功";
        		$this->ajaxReturn($arr,'JSON');
        	}
		}
		$where['id']=$user_auth['uid'];
        $mobile=M('follow')->where($where)->getField('mobile');
       	$this->assign('mobile',$mobile);
		$this->display();
	}
    /*代金劵*/
    public function discount(){
         /*获取用户*/
         $user_auth= cookie('user_auth');
         $user_id=$user_auth['uid'];
         /*代金劵*/
         $discount = M('futures_voucher_records');
         $voucher_where['user_id'] = $user_id;
         $voucher_where['count'] = array('gt',0);   
         $voucher_where['overdue_time'] = array('gt',time());
         $vouchers = $discount->where($voucher_where)->select();// 查询满足要求的总记录数
         $this->assign('vouchers',$vouchers);
        $this->display();
    }
	/*注册用户送卡券*/
	public function register_card($id,$card_id){
		$udata=M('follow')->find($id);
		//查询卡券信息
		$where_card=array(
			'status'=>1,
			'id'=>$card_id,
		);
		$cardData=M('futures_voucher')->where($where_card)->find();
		if(empty($cardData)){
			return false;
		}
		//为注册用户添加卡券
		$cwhere=array(
			'user_id'=>$id,
			'voucher_id'=>$card_id,
		);
		$res=M('futures_voucher_records')->where($cwhere)->find();
		if(!$res){
			$data=array(
					'user_id'=>$id,
					'voucher_id'=>$card_id,
					'money'=>$cardData['money'],
					'count'=>1,
					'overdue_time'=>$cardData['end_time'],
					'create_time'=>time(),
			);
			M('futures_voucher_records')->add($data);
		}

		//为注册用户上级添加卡券
		if($udata['route']){
			//获取上级id
			$arr=explode(',',$udata['route']);
			$lastid=array_pop($arr);
			$cardWhere=array(
					'user_id'=>$lastid,
					'voucher_id'=>$card_id,
			);
			$result=M('futures_voucher_records')->where($cardWhere)->find();
			if($result && $result['count']<$cardData['person_limit']){
				$updatedata=array(
						'count'=>$result['count']+1,
						'money'=>$cardData['money'],
						'overdue_time'=>$cardData['end_time'],
						'create_time'=>time(),
				);
				M('futures_voucher_records')->where($cardWhere)->save($updatedata);
			}else{
                /*
				$lastdata=array(
						'user_id'=>$lastid,
						'voucher_id'=>$card_id,
						'money'=>$cardData['money'],
						'count'=>1,
						'overdue_time'=>$cardData['end_time'],
						'create_time'=>time(),
				);
				M('futures_voucher_records')->add($lastdata);
                */
			}

		}

	}
}
